#include <iostream>
#include <string>
#include <vector>
#include <stdexcept>
#include <limits>
#include <iomanip>
#include <regex>

// 网络编程头文件
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>

// JSON库
#include "json.hpp"

using json = nlohmann::json;

// --- 实用工具命名空间 ---
namespace ClientUtils
{
    void clearCin()
    {
        std::cin.clear();
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    }

    bool isUsernameValid(const std::string &name)
    {
        std::regex pattern("^[a-zA-Z0-9]{3,18}$");
        return std::regex_match(name, pattern);
    }

    bool isPasswordValid(const std::string &password)
    {
        std::regex pattern("^[a-zA-Z0-9]{5,12}$");
        return std::regex_match(password, pattern);
    }
}

// --- 网络通信辅助工具 ---
namespace SocketUtils
{
    bool sendMessage(int sock, const std::string &msg)
    {
        if (sock < 0)
            return false;
        uint32_t len = htonl(msg.length());
        if (send(sock, &len, sizeof(len), 0) == -1)
            return false;
        if (send(sock, msg.c_str(), msg.length(), 0) == -1)
            return false;
        return true;
    }

    bool receiveMessage(int sock, std::string &msg)
    {
        if (sock < 0)
            return false;
        uint32_t len;
        ssize_t bytes_received = recv(sock, &len, sizeof(len), 0);
        if (bytes_received <= 0)
            return false;
        len = ntohl(len);
        if (len == 0)
        {
            msg = "";
            return true;
        }
        std::vector<char> buffer(len);
        bytes_received = recv(sock, buffer.data(), len, MSG_WAITALL);
        if (bytes_received <= 0)
            return false;
        msg.assign(buffer.begin(), buffer.end());
        return true;
    }
}

// --- API客户端核心 ---
class ApiClient
{
private:
    std::string server_ip;
    int server_port;
    int sock_fd = -1;

    json sendRequest(const json &request)
    {
        if (sock_fd < 0)
            throw std::runtime_error("未连接到服务器");
        if (!SocketUtils::sendMessage(sock_fd, request.dump()))
        {
            sock_fd = -1;
            throw std::runtime_error("发送请求失败, 服务器可能已断开连接。");
        }
        std::string response_str;
        if (!SocketUtils::receiveMessage(sock_fd, response_str))
        {
            sock_fd = -1;
            throw std::runtime_error("接收响应失败。服务器可能已断开连接。");
        }
        return json::parse(response_str);
    }

public:
    ApiClient(const std::string &ip, int port) : server_ip(ip), server_port(port) {}
    ~ApiClient() { disconnectFromServer(); }

    bool connectToServer()
    {
        if (sock_fd >= 0)
            close(sock_fd);
        sock_fd = socket(AF_INET, SOCK_STREAM, 0);
        if (sock_fd < 0)
        {
            perror("Socket creation error");
            return false;
        }
        struct sockaddr_in serv_addr;
        serv_addr.sin_family = AF_INET;
        serv_addr.sin_port = htons(server_port);
        if (inet_pton(AF_INET, server_ip.c_str(), &serv_addr.sin_addr) <= 0)
        {
            close(sock_fd);
            sock_fd = -1;
            perror("Invalid address");
            return false;
        }
        if (connect(sock_fd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
        {
            close(sock_fd);
            sock_fd = -1;
            perror("Connection Failed");
            return false;
        }
        std::cout << "已成功连接到服务器。\n";
        return true;
    }

    void disconnectFromServer()
    {
        if (sock_fd >= 0)
        {
            std::cout << "正在从服务器断开连接...\n";
            close(sock_fd);
            sock_fd = -1;
        }
    }

    bool isConnected() const { return sock_fd >= 0; }

    // --- 完整API方法列表 ---
    json login(const std::string &u, const std::string &p) { return sendRequest({{"action", "LOGIN"}, {"payload", {{"username", u}, {"password", p}}}}); }
    json registerUser(const std::string &u, const std::string &p, const std::string &t) { return sendRequest({{"action", "REGISTER"}, {"payload", {{"username", u}, {"password", p}, {"userType", t}}}}); }
    json getUserInfo(int uid) { return sendRequest({{"action", "GET_USER_INFO"}, {"payload", {{"userId", uid}}}}); }
    json changeUsername(int uid, const std::string &newName) { return sendRequest({{"action", "CHANGE_USERNAME"}, {"payload", {{"userId", uid}, {"newUsername", newName}}}}); }
    json changePassword(int uid, const std::string &newPass) { return sendRequest({{"action", "CHANGE_PASSWORD"}, {"payload", {{"userId", uid}, {"newPassword", newPass}}}}); }
    json rechargeBalance(int uid, double amount) { return sendRequest({{"action", "RECHARGE"}, {"payload", {{"userId", uid}, {"amount", amount}}}}); }
    json isUsernameExist(const std::string &username) { return sendRequest({{"action", "CHECK_USERNAME"}, {"payload", {{"username", username}}}}); }

    json getAllProducts() { return sendRequest({{"action", "GET_ALL_PRODUCTS"}, {"payload", {}}}); }
    json getMyProducts(int sellerId) { return sendRequest({{"action", "GET_MY_PRODUCTS"}, {"payload", {{"sellerId", sellerId}}}}); }

    json getCart(int userId) { return sendRequest({{"action", "GET_CART"}, {"payload", {{"userId", userId}}}}); }
    json addToCart(int uid, const std::string &pid, int q) { return sendRequest({{"action", "ADD_TO_CART"}, {"payload", {{"userId", uid}, {"productId", pid}, {"quantity", q}}}}); }
    json updateCartItem(int uid, const std::string &pid, int nq) { return sendRequest({{"action", "UPDATE_CART_ITEM"}, {"payload", {{"userId", uid}, {"productId", pid}, {"newQuantity", nq}}}}); }
    json clearCart(int userId) { return sendRequest({{"action", "CLEAR_CART"}, {"payload", {{"userId", userId}}}}); }

    json createOrder(int userId) { return sendRequest({{"action", "CREATE_ORDER"}, {"payload", {{"userId", userId}}}}); }
    json getUnpaidOrders(int userId) { return sendRequest({{"action", "GET_UNPAID_ORDERS"}, {"payload", {{"userId", userId}}}}); }
    json payOrder(int userId, const std::string &oid) { return sendRequest({{"action", "PAY_ORDER"}, {"payload", {{"userId", userId}, {"orderId", oid}}}}); }
    json cancelOrder(int userId, const std::string &oid) { return sendRequest({{"action", "CANCEL_ORDER"}, {"payload", {{"userId", userId}, {"orderId", oid}}}}); }
};

// --- 用户会话状态 ---
struct UserSession
{
    bool isLoggedIn = false;
    int userId = -1;
    std::string username;
    std::string userType;
    json fullUserData;

    void updateBalance(double newBalance)
    {
        if (fullUserData.is_object())
        {
            fullUserData["balance"] = newBalance;
        }
    }
    double getBalance() const
    {
        if (!fullUserData.is_object())
        {
            std::cerr << "获取用户信息失败。\n";
            return 0.0;
        }
        return fullUserData.value("balance", 0.0);
    }
};

// --- UI显示辅助函数 ---
namespace DisplayUtils
{
    void displayProducts(const json &products_data)
    {
        if (!products_data.is_array() || products_data.empty())
        {
            std::cout << "平台上当前没有商品。\n";
            return;
        }
        std::cout << "\n--- 平台商品列表 ---\n";
        std::cout << std::left << std::setw(10) << "ID" << std::setw(30) << "名称"
                  << std::setw(15) << "价格(¥)" << std::setw(10) << "库存" << std::endl;
        std::cout << "-------------------------------------------------------------\n";
        for (const auto &p : products_data)
        {
            double price = p.value("originalPrice", 0.0) * (1.0 - p.value("discountRate", 0.0));
            int available_stock = p.value("quantity", 0) - p.value("frozenQuantity", 0);
            std::cout << std::left << std::setw(10) << p.value("id", "")
                      << std::setw(30) << p.value("name", "")
                      << std::fixed << std::setprecision(2) << std::setw(15) << price
                      << std::setw(10) << available_stock << std::endl;
        }
        std::cout << "-------------------------------------------------------------\n";
    }
    void displayOrders(const json &orders_data)
    {
        if (!orders_data.is_array() || orders_data.empty())
        {
            std::cout << "没有找到相关订单。\n";
            return;
        }
        std::cout << "\n--- 订单列表 ---\n";
        std::cout << std::left << std::setw(5) << "序号" << std::setw(30) << "订单ID"
                  << std::setw(25) << "状态" << std::setw(15) << "总金额(¥)" << std::endl;
        std::cout << "--------------------------------------------------------------------------\n";
        int index = 1;
        for (const auto &order : orders_data)
        {
            std::cout << std::left << std::setw(5) << index++
                      << std::setw(30) << order.value("orderId", "")
                      << std::setw(25) << order.value("status", "")
                      << std::fixed << std::setprecision(2) << std::setw(15) << order.value("totalAmount", 0.0)
                      << std::endl;
        }
        std::cout << "--------------------------------------------------------------------------\n";
    }
    void displayCart(const json &cart_data)
    {
        if (!cart_data.is_object() || !cart_data.contains("items") || cart_data["items"].empty())
        {
            std::cout << "购物车是空的。\n";
            return;
        }
        std::cout << "\n--- 购物车详情 ---\n";
        std::cout << std::left << std::setw(10) << "商品ID" << std::setw(30) << "名称"
                  << std::setw(10) << "数量" << std::setw(15) << "单价(¥)" << std::endl;
        std::cout << "-----------------------------------------------------------------\n";
        for (const auto &item : cart_data["items"])
        {
            double price = item.value("originalPrice", 0.0) * (1.0 - item.value("discountRate", 0.0));
            std::cout << std::left << std::setw(10) << item.value("id", "")
                      << std::setw(30) << item.value("name", "")
                      << std::setw(10) << item.value("quantityInCart", 0)
                      << std::fixed << std::setprecision(2) << std::setw(15) << price
                      << std::endl;
        }
        std::cout << "-----------------------------------------------------------------\n";
        std::cout << "总价: ¥" << std::fixed << std::setprecision(2) << cart_data.value("totalPrice", 0.0) << std::endl;
    }
    void showProductPortal(const json &all_products_data)
    {
        int choice;
        while (true)
        {
            std::cout << "\n--- 查看和搜索商品 ---\n";
            std::cout << "1. 查看所有商品\n";
            std::cout << "2. 按名称搜索商品\n";
            std::cout << "3. 按分类查看商品\n";
            std::cout << "0. 返回上一级菜单\n";
            std::cout << "请输入您的选择: ";

            std::cin >> choice;
            if (std::cin.fail())
            {
                ClientUtils::clearCin();
                std::cout << "无效输入。\n";
                continue;
            }
            ClientUtils::clearCin();

            if (choice == 0)
                break;

            switch (choice)
            {
            case 1:
            { // 查看所有
                displayProducts(all_products_data);
                break;
            }
            case 2:
            { // 按名称搜索
                std::string query;
                std::cout << "请输入商品名称关键字: ";
                std::getline(std::cin, query);

                // 将搜索关键字转为小写，以便不区分大小写搜索
                std::transform(query.begin(), query.end(), query.begin(), ::tolower);

                json search_results = json::array();
                for (const auto &product : all_products_data)
                {
                    std::string name = product.value("name", "");
                    std::transform(name.begin(), name.end(), name.begin(), ::tolower);
                    if (name.find(query) != std::string::npos)
                    {
                        search_results.push_back(product);
                    }
                }
                displayProducts(search_results);
                break;
            }
            case 3:
            { // 按分类查看
                std::string category;
                std::cout << "请输入商品分类 (Book, Clothing, Food): ";
                std::getline(std::cin, category);

                json category_results = json::array();
                for (const auto &product : all_products_data)
                {
                    if (product.value("category", "") == category)
                    {
                        category_results.push_back(product);
                    }
                }
                displayProducts(category_results);
                break;
            }
            default:
                std::cout << "无效的选项。\n";
            }
        }
    }
}

class CustomerPortal;
class SellerPortal;

// ======================================================================================
// ============================= CUSTOMER PORTAL CLASS ================================
// ======================================================================================
class CustomerPortal
{
private:
    ApiClient &apiClient;
    UserSession &session;

    // --- 各菜单选项对应的私有方法 ---
    void viewAllProducts()
    {
        json response = apiClient.getAllProducts();
        

        if (response["status"] == "SUCCESS")
        {
            DisplayUtils::displayProducts(response["data"]);
        }
        else
        {
            std::cout << "获取商品失败: " << response.value("message", "未知错误") << std::endl;
        }
    }

    void viewAndSearchProducts()
    {
        try
        {
            json response = apiClient.getAllProducts();
            if (response["status"] == "SUCCESS")
            {
                // 进入商品门户，传入从服务器获取的所有商品数据
                DisplayUtils::showProductPortal(response["data"]);
            }
            else
            {
                std::cout << "获取商品失败: " << response.value("message", "未知错误") << std::endl;
            }
        }
        catch (const std::exception &e)
        {
            std::cerr << "操作失败: " << e.what() << std::endl;
        }
    }

    void showBalance()
    {
        session.fullUserData = apiClient.getUserInfo(session.userId);
        std::cout << "您的当前余额为: ¥" << std::fixed << std::setprecision(2) << session.getBalance() << "\n";
    }

    void recharge()
    {
        double amount;
        std::cout << "请输入充值金额: ";
        std::cin >> amount;
        if (std::cin.fail() || amount <= 0)
        {
            ClientUtils::clearCin();
            std::cout << "无效的金额。\n";
            return;
        }
        ClientUtils::clearCin();
        json response = apiClient.rechargeBalance(session.userId, amount);
        std::cout << "服务器响应: " << response.value("message", "") << std::endl;
        if (response["status"] == "SUCCESS")
        {
            session.updateBalance(response["data"]["newBalance"]);
        }
    }

    void changeUsername()
    {
        std::string newName;
        std::cout << "请输入新用户名: ";
        std::cin >> newName;
        
        while (1)
        {
            json response_for_username = apiClient.isUsernameExist(newName);
            if (!ClientUtils::isUsernameValid(newName))
            {
                std::cout << "用户名格式无效，请重新输入或输入cancel退出:";
                std::cin >> newName;
                if (newName == "cancel")
                {
                    return;
                }
            }
            else if (response_for_username["data"]["exists"])
            {
                std::cout << "用户名已存在，请重新输入或输入cancel退出:";
                std::cin >> newName;
                if (newName == "cancel")
                {
                    return;
                }
            }
            else
                break;
        }
        json response = apiClient.changeUsername(session.userId, newName);
        std::cout << "服务器响应: " << response.value("message", "") << std::endl;
        if (response["status"] == "SUCCESS")
        {
            session.username = newName;
        }
    }

    void addProductToCart()
    {
        viewAllProducts(); // 先展示商品列表
        std::string pid;
        int qty;
        std::cout << "请输入要添加的商品ID: ";
        std::cin >> pid;
        std::cout << "请输入数量: ";
        std::cin >> qty;
        ClientUtils::clearCin(); // 清理缓冲区
        if (qty <= 0)
        {
            std::cout << "数量必须为正数。\n";
            return;
        }
        json response = apiClient.addToCart(session.userId, pid, qty);
        std::cout << "服务器响应: " << response.value("message", "") << std::endl;
    }

    void createOrderFromCart()
    {
        json response = apiClient.createOrder(session.userId);
        std::cout << "服务器响应: " << response.value("message", "") << std::endl;
        if (response["status"] == "SUCCESS")
        {
            std::cout << "新订单详情: " << response["data"].dump(2) << std::endl;
        }
    }

    void changePassword()
    {
        std::string newPassWord;
        std::cout << "请输入新密码: ";
        std::cin >> newPassWord;
        if (!ClientUtils::isPasswordValid(newPassWord))
        {
            std::cout << "密码格式无效。\n";
            return;
        }
        json response = apiClient.changePassword(session.userId, newPassWord);
        std::cout << "服务器响应: " << response.value("message", "") << std::endl;
    }

    void manageCart()
    {
        while (true)
        {
            json response = apiClient.getCart(session.userId);
            if (response["status"] != "SUCCESS")
            {
                std::cout << "无法获取购物车: " << response.value("message", "") << std::endl;
                return;
            }
            DisplayUtils::displayCart(response["data"]);

            std::cout << "\n--- 管理购物车 ---\n";
            std::cout << "1. 修改商品数量\n2. 移除商品\n3. 清空购物车\n4. 生成订单\n0. 返回\n";
            std::cout << "请输入选择: ";
            int choice;
            std::cin >> choice;
            ClientUtils::clearCin();

            if (choice == 0)
                break;

            if (response["data"]["items"].empty() && choice != 0)
            {
                std::cout << "购物车是空的。\n";
                continue;
            }

            switch (choice)
            {
            case 1:
            { // 修改数量
                std::string pid;
                int nq;
                std::cout << "请输入要修改数量的商品ID: ";
                std::cin >> pid;
                std::cout << "请输入新的数量 (输入0则移除): ";
                std::cin >> nq;
                ClientUtils::clearCin();
                json update_resp = apiClient.updateCartItem(session.userId, pid, nq);
                std::cout << "服务器响应: " << update_resp.value("message", "") << std::endl;
                break;
            }
            case 2:
            { // 移除商品
                std::string pid;
                std::cout << "请输入要移除的商品ID: ";
                std::cin >> pid;
                // 简化处理，直接将数量更新为0来移除
                json remove_resp = apiClient.updateCartItem(session.userId, pid, 0);
                std::cout << "服务器响应: " << remove_resp.value("message", "") << std::endl;
                break;
            }
            case 3:
            {
                json clr_resp = apiClient.clearCart(session.userId);
                std::cout << "服务器响应: " << clr_resp.value("message", "") << std::endl;
                break;
            }
            case 4:
            {
                json order_resp = apiClient.createOrder(session.userId);
                std::cout << "服务器响应: " << order_resp.value("message", "") << std::endl;
                if (order_resp["status"] == "SUCCESS")
                {
                    std::cout << "新订单详情: " << order_resp["data"].dump(2) << std::endl;
                    return; // 生成订单后退出购物车管理
                }
                break;
            }
            }
        }
    }

    void manageOrders()
    {
        while (true)
        {
            if (!apiClient.isConnected()) // 如果连接中断，则退出
            {
                std::cout << "连接已中断，将自动退出" << std::endl;
                return;
            }

            std::cout << "\n--- 管理我的订单 ---\n";
            // 1. 首先获取并展示未支付的订单列表
            json response = apiClient.getUnpaidOrders(session.userId);

            if (response.value("status", "ERROR") != "SUCCESS" || !response.contains("data") || response["data"].empty())
            {
                std::cout << "您没有未支付的订单。\n";
                std::cout << "输入 0 返回主菜单: ";
            }
            else
            {
                DisplayUtils::displayOrders(response["data"]);
                std::cout << "\n--- 请选择操作 ---\n";
                std::cout << "1. 支付订单\n";
                std::cout << "2. 取消订单\n";
                std::cout << "0. 返回主菜单\n";
            }
            std::cout << "请输入您的选择: ";

            int choice;
            std::cin >> choice;
            ClientUtils::clearCin();

            if (choice == 0)
                break;

            // 如果没有订单，则不继续执行后续逻辑
            if (response.value("status", "ERROR") != "SUCCESS" || !response.contains("data") || response["data"].empty())
            {
                continue;
            }

            int order_idx;
            std::string action_prompt = (choice == 1) ? "支付" : "取消";

            std::cout << "请输入要" << action_prompt << "的订单序号: ";
            std::cin >> order_idx;
            ClientUtils::clearCin();

            if (order_idx > 0 && order_idx <= response["data"].size())
            {
                std::string oid = response["data"][order_idx - 1]["orderId"];
                json final_resp;

                if (choice == 1)
                { // 支付
                    if (session.getBalance() < response["data"][order_idx - 1].value("totalAmount", 0.0))
                    {
                        std::cout << "错误：您的余额不足以支付此订单。\n";
                        continue;
                    }
                    final_resp = apiClient.payOrder(session.userId, oid);
                }
                else
                { // 取消
                    final_resp = apiClient.cancelOrder(session.userId, oid);
                }
                std::cout << "服务器响应: " << final_resp.value("message", "无消息。") << std::endl;
            }
            else
            {
                std::cout << "无效的订单序号。\n";
            }
            break;
        }
    }

public:
    CustomerPortal(ApiClient &client, UserSession &sess) : apiClient(client), session(sess) {}

    void run()
    {
        int choice;
        while (true)
        {
            if (!apiClient.isConnected())
            {
                std::cout << "\n与服务器的连接已断开，请重新登录。\n";
                session.isLoggedIn = false;
                return;
            }

            std::cout << "\n--- 顾客主菜单 (" << session.username << ") ---\n";
            std::cout << "1. 查看和搜索商品\n";
            std::cout << "2. 查询余额\n";
            std::cout << "3. 充值余额\n";
            std::cout << "4. 修改账户名称\n";
            std::cout << "5. 修改账户密码\n";
            std::cout << "6. 添加商品到购物车\n";
            std::cout << "7. 查看并管理购物车\n";
            std::cout << "8. 管理我的订单\n";
            std::cout << "0. 退出登录\n";
            std::cout << "请输入您的选择: ";

            std::cin >> choice;
            if (std::cin.fail())
            {
                ClientUtils::clearCin();
                std::cout << "无效输入。\n";
                continue;
            }
            ClientUtils::clearCin();

            try
            {
                switch (choice)
                {
                case 1:
                    viewAndSearchProducts();
                    break;
                case 2:
                    showBalance();
                    break;
                case 3:
                    recharge();
                    break;
                case 4:
                    changeUsername();
                    break;
                case 5:
                    changePassword();
                    break;
                case 6:
                    addProductToCart();
                    break;
                case 7:
                    manageCart();
                    break;
                case 8:
                    manageOrders();
                    break;
                case 0:
                    session.isLoggedIn = false;
                    return;
                default:
                    std::cout << "无效的选项。\n";
                }
            }
            catch (const std::exception &e)
            {
                std::cerr << "操作失败: " << e.what() << std::endl;
            }
        }
    }
};

class SellerPortal
{
private:
    ApiClient &apiClient;
    UserSession &session;

    void viewMyProducts()
    {
        json response = apiClient.getMyProducts(session.userId);
        if (response["status"] == "SUCCESS")
        {
            DisplayUtils::displayProducts(response["data"]);
        }
        else
        {
            std::cout << "获取您的商品列表失败: " << response.value("message", "") << std::endl;
        }
    }

    void showBalance()
    {
        session.fullUserData = apiClient.getUserInfo(session.userId);
        std::cout << "您的当前余额为: ¥" << std::fixed << std::setprecision(2) << session.getBalance() << "\n";
    }

public:
    SellerPortal(ApiClient &c, UserSession &s) : apiClient(c), session(s) {}

    void run()
    {
        int choice;
        while (apiClient.isConnected() && session.isLoggedIn)
        {
            std::cout << "\n--- 商家主菜单 (" << session.username << ") ---\n";
            std::cout << "1. 查看余额\n2. 查看我的商品\n0. 退出登录\n";
            std::cout << "请输入您的选择: ";
            std::cin >> choice;
            ClientUtils::clearCin();
            try
            {
                switch (choice)
                {
                case 1:
                    showBalance();
                    break;
                case 2:
                    viewMyProducts();
                    break;
                case 0:
                    session.isLoggedIn = false;
                    return;
                default:
                    std::cout << "无效选项。\n";
                }
            }
            catch (const std::exception &e)
            {
                std::cerr << "操作失败: " << e.what() << std::endl;
            }
        }
    }
};

// ======================================================================================
// ============================= MAIN APPLICATION CLASS ===============================
// ======================================================================================
class ECommerceClient
{
private:
    ApiClient apiClient;
    UserSession session;

    void handleLogin()
    {
        if (!apiClient.connectToServer())
        {
            std::cerr << "错误：无法连接到服务器！请确认服务器正在运行。\n";
            return;
        }
        std::string user, pass;
        std::cout << "请输入用户名: ";
        std::getline(std::cin, user);
        std::cout << "请输入密码: ";
        std::getline(std::cin, pass);

        json response = apiClient.login(user, pass);
        if (response["status"] == "SUCCESS")
        {
            session.isLoggedIn = true;
            session.fullUserData = response["data"];
            session.userId = session.fullUserData["id"];
            session.username = session.fullUserData["name"];
            session.userType = session.fullUserData["usertype"];
            std::cout << "登录成功！欢迎, " << session.username << "!\n";
        }
        else
        {
            std::cout << "登录失败: " << response.value("message", "未知错误") << std::endl;
            apiClient.disconnectFromServer();
        }
    }

    void handleRegister()
    {
        if (!apiClient.connectToServer())
        {
            std::cerr << "错误：无法连接到服务器！请确认服务器正在运行。\n";
            return;
        }
        std::string regUsername, regPassword, confirmPassword, regUserType;
        int typeChoiceNum;
        std::cout << "--- 用户注册 ---\n";
        std::cout << "请输入用户名 (3-18位字母或数字): ";
        std::cin >> regUsername;
        while (1)
        {
            json response_for_username = apiClient.isUsernameExist(regUsername);
            if (!ClientUtils::isUsernameValid(regUsername))
            {
                std::cout << "用户名格式无效，请重新输入或输入cancel退出:";
                std::cin >> regUsername;
                if (regUsername == "cancel")
                {
                    return;
                }
            }
            else if (response_for_username["data"]["exists"])
            {
                std::cout << "用户名已存在，请重新输入或输入cancel退出:";
                std::cin >> regUsername;
                if (regUsername == "cancel")
                {
                    return;
                }
            }
            else
                break;
        }
        std::cout << "请输入密码 (5-12位字母或数字): ";
        std::getline(std::cin, regPassword);
        while (!ClientUtils::isPasswordValid(regPassword))
        {
            std::cout << "密码格式错误！请重新输入: ";
            std::getline(std::cin, regPassword);
        }
        std::cout << "请再次输入密码以确认: ";
        std::getline(std::cin, confirmPassword);
        while (regPassword != confirmPassword)
        {
            std::cout << "两次输入的密码不一致，请重试。\n";
            std::cout << "请再次输入确认密码: ";
            std::getline(std::cin, confirmPassword);
        }
        std::cout << "请选择用户类型 (1. 商家, 2. 消费者): ";
        while (!(std::cin >> typeChoiceNum) || (typeChoiceNum != 1 && typeChoiceNum != 2))
        {
            std::cout << "无效选择。请输入 1 (商家) 或 2 (消费者): ";
            ClientUtils::clearCin();
        }
        regUserType = (typeChoiceNum == 1) ? "Seller" : "Customer";
        json response = apiClient.registerUser(regUsername, regPassword, regUserType);
        std::cout << "服务器响应: " << response.value("message", "无消息") << std::endl;
        apiClient.disconnectFromServer();
    }

    void handleGuestBrowse()
    {
        try
        {
            if (!apiClient.connectToServer())
            {
                std::cerr << "错误：无法连接到服务器！请确认服务器正在运行。\n";
                return;
            }
            json response = apiClient.getAllProducts();
            apiClient.disconnectFromServer(); // 游客操作，获取完数据就断开

            if (response["status"] == "SUCCESS")
            {
                // 进入商品门户，传入从服务器获取的所有商品数据
                DisplayUtils::showProductPortal(response["data"]);
            }
            else
            {
                std::cout << "获取商品失败: " << response.value("message", "未知错误") << std::endl;
            }
        }
        catch (const std::exception &e)
        {
            std::cerr << "\n!! 操作失败: " << e.what() << std::endl;
            apiClient.disconnectFromServer();
        }
    }

public:
    ECommerceClient(const std::string &ip, int port) : apiClient(ip, port) {}

    void run()
    {
        while (true)
        {
            if (!session.isLoggedIn)
            {
                int choice;
                std::cout << "\n欢迎来到电商平台客户端!\n";
                std::cout << "=========================\n";
                std::cout << "1. 用户登录\n";
                std::cout << "2. 用户注册\n";
                std::cout << "3. 浏览平台商品 (游客)\n";
                std::cout << "0. 退出平台\n";
                std::cout << "=========================\n";
                std::cout << "请输入您的选择: ";

                std::cin >> choice;
                if (std::cin.fail())
                {
                    ClientUtils::clearCin();
                    std::cout << "无效输入。\n";
                    continue;
                }
                ClientUtils::clearCin();

                try
                {
                    switch (choice)
                    {
                    case 1:
                        handleLogin();
                        break;
                    case 2:
                        handleRegister();
                        break;
                    case 3:
                        handleGuestBrowse();
                        break;
                    case 0:
                        std::cout << "感谢使用，再见！\n";
                        return;
                    default:
                        std::cout << "无效选项。\n";
                    }
                }
                catch (const std::exception &e)
                {
                    std::cerr << "\n!! 操作失败: " << e.what() << std::endl;
                    apiClient.disconnectFromServer();
                }
            }
            else
            { // 如果已登录
                if (session.userType == "Customer")
                {
                    CustomerPortal customerPortal(apiClient, session);
                    customerPortal.run();
                }
                else if (session.userType == "Seller")
                {
                    SellerPortal sellerPortal(apiClient, session);
                    sellerPortal.run();
                }
                apiClient.disconnectFromServer();
            }
        }
    }
};

int main()
{
    const std::string SERVER_IP = "127.0.0.1";
    const int SERVER_PORT = 8888;

    ECommerceClient clientApp(SERVER_IP, SERVER_PORT);
    clientApp.run();

    return 0;
}
